<template>
    <!-- 首页/详情页 -->
    <!-- h5 滚动穿透不需要处理，wx、app 需要 使用 page-meta 组件配合阻止滚动穿透 -->
    <page-meta :page-style="'overflow:' + (false ? 'hidden' : 'visible')"></page-meta>
    <view class="detail">
        <!-- 详细信息 -->
        <info-list :item="info" isDetail @mark="handleMark">
            <view class="text-30 my-20 text-gray-600">{{ info.content }}</view>
        </info-list>
        <u-gap height="20" bgColor="#F9FAFB"></u-gap>
        <view class="p-20 text-30 font-bold">
            评论<text class="ml-10"></text>
        </view>
        <!-- 评论列表 -->
        <view class="comment-list">
            <view v-for="comment in comments" :key="comment.id" class="comment-item mb-20">
                <!-- 头像 -->
                <image 
                	class="rounded-full mr-20 clickable"
                	:src="comment.avatarUrl" 
                	mode="aspectFill"
                	style="width: 100rpx;height: 100rpx;"
                	@click="gotoProfile(comment.userId)">
                </image>
                <view class="flex-1 flex flex-col">
                    <view class="flex justify-between items-center">
                        <view class="text-28 font-bold text-blue">{{ comment.username }}</view>
                        <view 
                            v-if="isMyComment(comment.userId)"
                            class="text-red-500 text-24 delete-btn"
                            @click="deleteComment(comment.id)">
                            删除
                        </view>
                    </view>
                    <view 
                        class="comment-text text-26 my-10" 
                        :class="{ 'line-clamp': !comment.isExpanded && comment.content.length > 50 }">
                        {{ comment.content }}
                    </view>
                    
                    <!-- 展开按钮 -->
                    <view 
                        v-if="comment.content.length > clampLength"
                        class="text-blue text-24 mt-10" 
                        @click="toggleClamp(comment)">
                        {{ comment.isExpanded ? '收起' : '展开全文' }}
                    </view>
                    <!-- 可选时间 -->
                    <view class="flex justify-between text-24 my-10">
                        <view class="text-gray-500">{{ formatTime(comment.createTime) }}</view>
                    </view>
                </view>
            </view>
        </view>
        <!-- 底部操作栏 -->
        <view class="bottom-input">
        </view>
        <bottom-input @submit="submit"></bottom-input>
    </view>
</template>

<script>
import { detailInfo } from "@/utils/data/data.js";
import InfoList from "@/pages/home/cpns/info-list.vue";
import BottomInput from '@/components/bottom-input/bottom-input.vue';
import { PostApi,CommentsApi } from "@/api/index.js";
import { formatTime } from '@/utils/timeUtils';
import websocketMixin from '@/utils/mixins/websocketMixin';

export default {
	mixins: [websocketMixin],
    components: {
        InfoList,
        BottomInput
    },
    data() {
        return {
            postId: null,
            info: {},
            pageQuery: {
                pageNo: 1,
                pageSize: 10
            },
            comments: [],
			clampLength: 20
        }
    },
    onLoad(e) {
        if (e.postId) {
            this.postId = e.postId;
            this.loadPostDetail(this.postId);
            this.getPostComments();
        }
    },
    methods: {
        formatTime,
		 isLongComment(content) {
		    return content.length > this.clampLength;
		},
		toggleClamp(comment) {
		    this.$set(comment, 'isExpanded', !comment.isExpanded);
		},
        // 判断是否是当前用户发布的评论
        isMyComment(commentUserId) {
            const userId = getApp().globalData.userId;
            return commentUserId === userId;
        },
        // 根据id查询帖子详情
        async loadPostDetail(postId) {
            try {
                const res = await PostApi.getPostById(postId);
                this.info = res.data; // 或者根据实际返回结构调整
                uni.setNavigationBarTitle({
                    title: res.data.title
                })
            } catch (err) {
                console.error('Failed to load post detail:', err);
            }
        },
        // 根据id查询帖子评论
        async getPostComments() {
            try {
                const params = {
                    postId: this.postId,
                    ...this.pageQuery
                };
                const res = await CommentsApi.getCommentList(params);
                
                // 初始化每条评论的 isExpanded 属性
                this.comments = res.data.list.map(comment => ({
                    ...comment,
                    isExpanded: false
                }));
                
            } catch (err) {
                console.error('Failed to load post comments:', err);
            }
        },
		// 跳转到用户主页
		gotoProfile(userId) {
			const currentUserId = getApp().globalData.userId;
				
			// 判断是否是自己
			if (userId === currentUserId) {
				return; // 如果是自己，不跳转
			}
			uni.navigateTo({
				url: `/pages/paper/friend_profile?userId=${userId}`
			});
		},
        // 表情
        handleMark(item) {
            switch (item.value) {
                case 'smile':
                    if (this.info.infoNum.index == 1) return
                    else if (this.info.infoNum.index == 2) this.info.infoNum.cryNum--
                    this.info.infoNum.index = 1
                    this.info.infoNum.smileNum++
                    break;
                case 'cry':
                    if (this.info.infoNum.index == 2) return
                    else if (this.info.infoNum.index == 1) this.info.infoNum.smileNum--
                    this.info.infoNum.index = 2
                    this.info.infoNum.cryNum++
                    break
            }
            const title = item.value === 'smile' ? '谢谢表扬' : '继续加油'
            uni.showToast({
                title,
                icon: 'none',
            })
        },
        // 提交评论
        submit(data) {
            CommentsApi.addComment({
                postId: this.postId,
                content: data
            }).then(() => {
                uni.showToast({ title: '评论成功' });
                this.pageQuery.pageNo = 1;
                this.getPostComments(); // 刷新评论
				this.loadPostDetail(this.postId);
            });
        },
        async deleteComment(id) {
            uni.showModal({
                title: '提示',
                content: '确定要删除这条评论吗？',
                success: async (res) => {
                    if (res.confirm) {
                        try {
                            await CommentsApi.deleteComment(id);
                            uni.showToast({ title: '删除成功' });
                            this.pageQuery.pageNo = 1; // 重置分页
                            this.getPostComments(); // 重新加载评论
							this.loadPostDetail(this.postId);
                        } catch (err) {
                            console.error('删除评论失败:', err);
                            uni.showToast({ title: '删除失败', icon: 'none' });
                        }
                    }
                }
            });
        }
    }
}
</script>

<style lang="scss" scoped>
.detail {
    .comment {
        display: flex;
        margin: 20rpx;

        .comment-text {
            word-break: break-all; /* 长单词或 URL 自动换行 */
            white-space: normal;   /* 允许换行 */
            max-height: 200rpx;    /* 可选：设置最大高度防止内容过大 */
            overflow-y: auto;      /* 如果内容超限，允许内部滚动 */
        }

        .comment-replay {
            height: 40rpx;
        }
    }

    .bottom-input {
        height: 100rpx;
    }
}
.comment-list {
    padding: 0 20rpx;

    .comment-item {
        display: flex;
        align-items: flex-start;
        background-color: #fff;
        padding: 20rpx;
        border-radius: 16rpx;
        box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
        flex-direction: row; /* 确保头像和内容在一行 */
    }
    
    .delete-btn {
        margin-left: 15rpx;
        white-space: nowrap;
    }
    
    .text-red-500 {
        color: #ff4949;
    }
	
	.clickable {
		cursor: pointer;
		transition: opacity 0.3s ease;
		&:active {
			opacity: 0.7;
		}
	}
	
	.comment-text {
	    word-break: break-all;
	    white-space: normal;
	}
	
	.line-clamp {
	    display: -webkit-box;
	    -webkit-box-orient: vertical;
	    -webkit-line-clamp: 1; /* 显示3行后省略 */
	    overflow: hidden;
	}
}

</style>    